import fs from 'fs'
import path from 'path'
const BASE_DIR = "./store/appsFlyer"; // 所有文件生成到store/modules下
const apiFilePath = `${BASE_DIR}/api.js`;
const mutationsFilePath = `${BASE_DIR}/mutations.js`;
const actionsFilePath = `${BASE_DIR}/actions.js`;
const mutationTypesFilePath = `${BASE_DIR}/mutation-types.js`;
const gettersFilePath = `${BASE_DIR}/getters.js`;
try {

  // addStoreToFile('supplementHistoryList', 'console/appsflyer/data/get/supplement/historyList', 'Appsflyer 历史补发中台用户列表')
  // addStoreToFile('verifyTaskHistoryList', 'console/appsflyer/data/get/verify/task/historyList', 'Appsflyer 校验补发历史任务查询')
  // addStoreToFile('checkFakeOrder', 'console/appsflyer/data/check/fake/order', 'Appsflyer 订单事件真伪判断', 'post')
  // addStoreToFile('verifyMissingDevice', 'console/appsflyer/data/verify/missing/device', '校验 Appsflyer 漏报的设备信息', 'post')
  // addStoreToFile('checkBatchVerifyProcess', 'console/appsflyer/data/check/batch/verify/process', '前端定时轮询查询校验进度',)
  // addStoreToFile('verifyResult', 'console/appsflyer/data/get/verify/result', '查询Appsflyer 漏报校验结果',)
  // addStoreToFile('deleteSupplementHistory', 'appsflyer/data/delete/supplement/historyList', '删除历史补发', 'post')
  addStoreToFile('loginInfoList', 'appsflyer/data/get/user/login/info/list', 'Appsflyer 查询中台账号历史三个月的登录行为', 'get')


} catch (error) {
  console.error(error.message);
}
/**
 * 
 * @param {*} apiName  api名称
 * @param {*} apiUrl   api地址
 * @param {*} remark   api描述
 * @param {*} requestType   请求方式
 * @param {*} apiType  api类型['get', 'create', 'download', 'update', 'delete']
 * @returns 
 */
function addStoreToFile(
  apiName,
  apiUrl,
  remark = "",
  requestType = "get",
  apiType
) {
  try {
    _ensureDirectoryExists();
    // let newApiName = _getNewApiName(apiName, apiType);
    // 1. 添加 API
    addApiToFile(apiName, apiUrl, remark, requestType);


    // 2. 添加 addMutationTypes
    addMutationTypes(apiName, remark);
    // 3. 添加 getters
    addGettersToFile(apiName, remark);
    // 4. 添加 mutations
    addMutationsToFile(apiName, remark);
    // 5. 添加 actions
    addActionsToFile(apiName, remark, requestType);
    return "success";
  } catch (error) {
    console.error(error.message);
  }

}
function _firstUpperCase(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

/**
 * 文件生成规则
 * **/
// 1. api写入
function addApiToFile(apiName, apiUrl, remark = "", requestType, apiType) {
  let newApiName = apiName

  if (requestType == 'get') {
    //将apiName首字母大写，并前面拼接get
    newApiName = _firstUpperCase(apiName);
    newApiName = "get" + newApiName;
  }

  let isCorrect = _checkCorrect(
    apiFilePath,
    `export const ${newApiName} *= *['"].+['"]`,
    apiUrl
  );
  if (isCorrect) {
    const newApi = `
/**
 * ${remark} 
 */
export const ${newApiName} = '${apiUrl}';\n`;
    fs.appendFileSync(apiFilePath, newApi, "utf8");
    console.log(`接口 ${newApiName} 添加成功`);

    return `接口 ${newApiName} 添加成功`;
  }
}
// 2. mutation-types写入
function addMutationTypes(apiName, remark) {
  apiName = apiName.toUpperCase();
  let isCorrect1 = _checkCorrect(
    mutationTypesFilePath,
    `export const ${apiName + "_REQUEST"} *= *['"].+['"]`
  );
  let isCorrect2 = _checkCorrect(
    mutationTypesFilePath,
    `export const ${apiName + "_RECEIVE"} *= *['"].+['"]`
  );

  if (isCorrect1 && isCorrect2) {
    let newApi = `
/**
 * ${remark} 
 */
export const ${apiName + "_REQUEST"} = '${apiName + "_REQUEST"}';\n
export const ${apiName + "_RECEIVE"} = '${apiName + "_RECEIVE"}';\n`;
    fs.appendFileSync(mutationTypesFilePath, newApi, "utf8");
    console.log(`mutation-types ${apiName} 添加成功`);
    return `mutation-types ${apiName} 添加成功`;
  }
}
//3. getters 写入
async function addGettersToFile(apiName, remark) {
  // 1. 初始化文件（如果需要）
  if (!fs.existsSync(gettersFilePath)) {
    fs.writeFileSync(
      gettersFilePath,
      `
  export default { }
            `.trim(),
      "utf8"
    );
  }

  // 2. 读取最新内容（每次重新读取）
  let content = fs.readFileSync(gettersFilePath, "utf8");
  // 3. 处理state
  const getterRegex =
    /export\s+default\s*{([^{}]*?(?:\{[^{}]*\}[^{}]*?)*)}/;

  if (getterRegex.test(content)) {
    content = content.replace(getterRegex, (match, stateContent) => {
      if (
        new RegExp(`${apiName}Info\\s*:|${apiName}Status\\s*:`).test(
          stateContent
        )
      ) {
        throw new Error(`State中已存在${apiName}相关属性`);
      }
      return `export default {
    ${stateContent.trim()}
    ${remark ? `// ${remark}` : ""}
    ${apiName}Info,
    ${apiName}Status,
}`;
    });
  }
  // 创建内容导出
  let isCorrect1 = _checkCorrect(
    gettersFilePath,
    `const ${apiName + "Info"} *= *['"].+['"]`
  );
  let isCorrect2 = _checkCorrect(
    gettersFilePath,
    `const ${apiName + "Status"} *= *['"].+['"]`
  );
  if (isCorrect1 && isCorrect2) {


    let newApi = `
  /**
   * ${remark} 
   */
  const ${apiName + "Info"} = state =>state.${apiName + "Info"}||{};\n
  const ${apiName + "Status"} = state =>state.${apiName + "Status"
      }||'';\n`;

    newApi = newApi + content
    fs.writeFileSync(gettersFilePath, newApi, "utf8");
    console.log(`getters ${apiName} 添加成功`);
    return `getters ${apiName} 添加成功`;
  }
}
// 4. mutations 写入
function addMutationsToFile(apiName, remark) {
  // 1. 初始化文件（如果需要）
  if (!fs.existsSync(mutationsFilePath)) {
    fs.writeFileSync(
      mutationsFilePath,
      `
import * as type from './mutation-types'
export const state = {}
export const mutations = {}
        `.trim(),
      "utf8"
    );
  }

  // 2. 读取最新内容（每次重新读取）
  let content = fs.readFileSync(mutationsFilePath, "utf8");

  // 3. 处理state
  const stateRegex =
    /export\s+const\s+state\s*=\s*{([^{}]*?(?:\{[^{}]*\}[^{}]*?)*)}/; ///export\s+const\s+state\s*=//\s*{([\s\S]*?)}/;
  if (stateRegex.test(content)) {
    content = content.replace(stateRegex, (match, stateContent) => {
      if (
        new RegExp(`${apiName}Info\\s*:|${apiName}Status\\s*:`).test(
          stateContent
        )
      ) {
        throw new Error(`State中已存在${apiName}相关属性`);
      }
      return `export const state = {
    ${stateContent.trim()}
    ${remark ? `// ${remark}` : ""}
    ${apiName}Info: {},
    ${apiName}Status: '',
}`;
    });
  }

  // 4. 处理mutations（关键修正）
  const mutationRegex = /export\s+const\s+mutations\s*=\s*{([\s\S]*?)}\s*$/;
  if (mutationRegex.test(content)) {
    content = content.replace(mutationRegex, (match, mutationContent) => {
      if (
        new RegExp(
          `\\[type\\.${apiName.toUpperCase()}_(REQUEST|RECEIVE)\\]`
        ).test(mutationContent)
      ) {
        throw new Error(`Mutations中已存在${apiName}相关操作`);
      }
      return `export const mutations = {
    ${mutationContent.trim()}
    ${remark ? `// ${remark}` : ""}
    [type.${apiName.toUpperCase()}_REQUEST](state) {
        state.${apiName}Status = 'loading';
        state.${apiName}Info = {};
    },
    [type.${apiName.toUpperCase()}_RECEIVE](state, res) {
        state.${apiName}Status = 'loaded';
        state.${apiName}Info = res?.content || {};
    },
}`;
    });
  }

  // 5. 写入最终结果
  fs.writeFileSync(mutationsFilePath, content, "utf8");
  console.log(`${apiName}相关mutations配置已添加`);

  return `${apiName}相关mutations配置已添加`;
}
//5. actions.js
function addActionsToFile(apiName, remark, requestType) {
  // 1. 初始化文件（如果需要）
  if (!fs.existsSync(actionsFilePath)) {
    fs.writeFileSync(
      actionsFilePath,
      `
import * as type from './mutation-types'
import * as API from './api'
import { ajax } from '@/utils/fetch'
        `.trim(),
      "utf8"
    );
  }

  // 2. 读取最新内容（每次重新读取）
  let content = fs.readFileSync(actionsFilePath, "utf8");
  // 3. 判断文件中是否存在函数名称为apiName的函数
  if (_checkFunctionExists(content, apiName)) {
    throw new Error(`函数 ${apiName} 已存在`);
  }
  let newApiName = apiName
  if (requestType == 'get') {
    //将apiName首字母大写，并前面拼接get
    newApiName = _firstUpperCase(apiName);
    newApiName = "get" + newApiName;
  }
  // 4. 追加新函数
  const newAction = `
${remark ? `// ${remark}` : ""}  
export const ${newApiName} = ({ commit }, data) => {
    commit(type.${apiName.toUpperCase()}_REQUEST, data);
    return ajax.${requestType}(
        API.${newApiName},
        { commit },
        data,
        type.${apiName.toUpperCase()}_RECEIVE
    );
};`;

  fs.appendFileSync(actionsFilePath, newAction, "utf8");
  console.log(`${apiName}相关actions配置已添加`);
  return `${apiName}相关actions配置已添加`;
}



// 校验文件内是否已经存在
function _checkCorrect(filePath, regStr, apiUrl) {
  // 1. 检查文件是否存在
  if (!fs.existsSync(filePath)) {
    fs.writeFileSync(filePath, "", "utf8");
  }
  // 2. 读取文件内容
  const content = fs.readFileSync(filePath, "utf8");

  // 3. 检查接口是否已存在
  const apiRegex = new RegExp(regStr, "g");
  if (regStr && apiRegex.test(content)) {
    throw new Error(`已存在`);
  }

  // 4. 检查URL是否已存在
  if (apiUrl && content.includes(apiUrl)) {
    throw new Error(`接口地址 ${apiUrl} 已存在`);
  }
  return true;
}
// 匹配是否满足条件的函数
function _checkFunctionExists(content, apiName) {
  // 匹配两种函数定义方式：
  // 1. export const fnName = ({ commit }) => {...}
  // 2. export function fnName({ commit }) {...}
  const funcRegex = new RegExp(
    `export\\s+(?:const\\s+${apiName}\\s*=\\\s*\\(|function\\s+${apiName}\\s*\\\()`
  );
  return funcRegex.test(content);
}
// 重新设置名称
function _getNewApiName(apiName, requestType, apiType) {
  if (apiType) {
    // 将apiName首字母大写
    apiName = apiName.replace(apiName[0], apiName[0].toUpperCase());
    apiName = requestType == "get" ? requestType + apiName : apiType + apiName;
    return apiName;
  }
  return apiName;
}
// 在文件顶部添加创建目录的函数
function _ensureDirectoryExists() {
  if (!fs.existsSync(BASE_DIR)) {
    fs.mkdirSync(BASE_DIR, { recursive: true });
  }
}